// pages/goods/goods.js
var data = require('../../utils/data')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        drinkslist:[],
        drinksprice:0,
        orderslist:[],
        drinks:[],
        orderdrinks:[],
        odrinksid:[]
    },
    onLoad(){
        this.getAllDrink()
    },
    onShow() {
        this.getprice()
        this.getOrders()
    },
    //提交订单
    onSubmit(){
        // 购物车数据
        const list = data.goodList;
        //总计金额
        const price = this.data.drinksprice;
        console.log('购物车数据',list)
        //存入数据库饮品id数组
        const Llist =[];
        list.forEach(ele=>{
            Llist.push(ele.did)
        })
        console.log(Llist);
        wx.request({
            url: 'http://127.0.0.1:3000/order',
            method:'POST',
            data:{
               "drinksList":Llist+"",
               "price":this.data.drinksprice/100
            },
            success:(res)=>{
                wx.showToast({
                  title: '下单成功',
                  icon:'none',
                })
                data.goodList=[]
                this.onShow()   
            },
            fail:(err)=>{
                console.log(err)
            }
          })
    },
    //获取价格
    getprice(){
        var list = data.goodList;
        var price=0
        list.forEach(ele=>{
            price =price+ele.nprice
        })
        console.log(price)
        this.setData({
            drinkslist:data.goodList,
            drinksprice:price*100
        })
    },
    //获取所有订单
    getOrders(){
        const fdrinks =[];
        wx.request({
          url: 'http://127.0.0.1:3000/orders',
          method:'GET',
          success:(res)=>{
             console.log(res.data)
             this.setData({
                orderslist:res.data
             })
             this.data.orderslist.forEach(ele=>{
                const idrinks =[]
                console.log("订单的饮品id",ele.drinks_id.split(","))
                console.log(ele,ele)
                const sdrinks=ele.drinks_id.split(",")
                sdrinks.forEach(el=>{
                   idrinks.push(Number.parseInt(el))
                   console.log("数组",idrinks)
                })
                fdrinks.push(idrinks)
                console.log(fdrinks)
                this.setData({
                    odrinksid:fdrinks
                })
            })
          },
          fail:(err)=>{
              console.log(err)
          }
        })

    },
    //获取所有饮品
    getAllDrink(){
        wx.request({
            url: 'http://127.0.0.1:3000/drink',
            method:'GET',
            success:(res)=>{
               console.log(res.data)
               this.setData({
                drinks:res.data
               })
            },
            fail:(err)=>{
                console.log(err)
            }
          })
    }
})